<?php

namespace common\models\info;

use common\component\BaseActiveRecord;
use common\component\Constant;
use common\extension\bestedm\MailService;
use common\models\base\Periodical;
use common\utils\CommonUtil;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Query;

/**
 * This is the model class for table "{{%info_copyright_template}}".
 *
 * @property int $id
 * @property string $title
 * @property string $subject
 * @property string $description
 * @property string $content
 * @property int $type
 * @property int $status 状态
 * @property int $display 是否显示
 * @property int $target_id 第三方id
 * @property string $updated_at
 * @property string $created_at
 */
class Template extends BaseActiveRecord
{

    const STATUS_DELETE = -1;
    const STATUS_DISABLE  = 0;
    const STATUS_ENABLE = 1;


    const TYPE_COPYRIGHT = 1; //版权
    const TYPE_EMAIL = 2;  //邮件

    const DISPLAY_NO = 0; //隐藏
    const DISPLAY_YES = 1; //显示

    static $display_arr = [
        self::DISPLAY_NO => '隐藏',
        self::DISPLAY_YES => '显示',
    ];

    static $status_arr = [
        self::STATUS_DELETE => '删除',
        self::STATUS_DISABLE => '禁用',
        self::STATUS_ENABLE => '启用',
    ];
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%info_template}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['content'],'required'],
            [['id', 'status','target_id','type', 'updated_at', 'created_at','display'], 'integer'],
            [['title'], 'string', 'max' => 32],
            [['subject'],'string','max'=>255],
            [['description'],'string','max'=>1000],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '名称',
            'subject' =>'主题',
            'description' =>'描述',
            'content' => '内容',
            'type' => '类型',
            'status' => '状态',
            'display' => '是否显示',
            'target_id' => '第三方id',
            'updated_at' => '更新时间',
            'created_at' => '创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }
        if ($insert) {
            //如果是创建的邮件模板，则需要更新到第三方
            if ($this->type == self::TYPE_EMAIL) {
               $result = MailService::templateAdd($this->title,$this->subject,$this->content);
               if ($result['status'] != "success") {
                    $this->addError('target_id','上传到第三方服务失败,'.$result['data']);
                    return false;
               }
                $this->target_id = $result['data'];
            }
        } else {
            if ($this->type == self::TYPE_EMAIL && $this->target_id) {
                $result = MailService::templateModify($this->target_id,$this->title,$this->subject,$this->content);
                if ($result['status'] != "success") {
                    $this->addError("target_id","修改失败,".$result['data']);
                    return false;
                }
            }
        }
        return true;
    }

    public function afterDelete()
    {
        parent::afterDelete();
        //如果是邮件模板且已上传第三方服务器则删除
        if ($this->type == self::TYPE_EMAIL && $this->target_id) {
            MailService::templateRemove($this->target_id);
        }
    }

    public function afterFind()
    {
        parent::afterFind();
        $this->ui();
    }

    public function ui() {
        $this->ui["status"] = self::$status_arr[$this->status];
        $this->ui["display"] = self::$display_arr[$this->display];
    }


    public function dataListTable($post,$type = self::TYPE_COPYRIGHT) {
        //请求参数组装
        $where = ["and"];
        $where[] = ["=","type",$type];
        if (!empty($post['title'])) {
            $where[] = ['like','title',trim($post['title'])];
        }
        if (isset($post['status']) && $post['status'] == -1) {
            $where[] =['=','status',-1];
        } else {
            //删除的状态不显示在列表中
            $where[] = ['>','status',-1];
        }
        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;
    }

    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }

    /**
     * 小组件获取模板
     * @return  array  [id=>title,id=>title]
     */
    public static function arrEnableDropDownList($type = self::TYPE_COPYRIGHT) {
        $result = [['id'=>0,'text'=>"请选择版权申明"]];
        $models = static::find()->select("id,title")->where(['status'=>self::STATUS_ENABLE,'type'=>$type])->asArray()->all();
        if ($models) {
            foreach ($models as $model) {
                $result[] = ['id'=>$model['id'],'text'=>$model['title']];
            }
        }
        return $result;
    }


    /**
     * 获取缓存中的数据
     * @param $id
     * @param $field
     * @return string | null
     */
    public static function getFieldById($id,$field) {
        $data = self::loadRowById($id);
        return isset($data[$field]) ? $data[$field] : null;
    }


    public static function loadRowById($id) {
        $key = "crid:".$id;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $data = static::find()->where(['id'=>$id,'status'=>self::STATUS_ENABLE])->asArray()->one();
            if ($data) {
                CommonUtil::setCache(__CLASS__,$key,$data);
            }
        }
        return $data;
    }

    /**
     * 获取邮件模板
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getEmailTemplate() {
        return static::find()
            ->where(['type'=>self::TYPE_EMAIL,'status'=>self::STATUS_ENABLE])
            ->andWhere(['>','target_id',0])
            ->asArray()
            ->all();
    }

    public static function getTemplateList($page=1,$pageSize=10) {
        $cache_key = "template_arr_page:".$page;
        $data = CommonUtil::getCache(__CLASS__,$cache_key);
        if (!$data) {
            $q = (new Query())->from(self::tableName())
                ->select("info_template.*")
                ->join('left join','base_periodical','info_template.id = base_periodical.template_id')
                ->where(["base_periodical.status"=>Periodical::STATUS_FINISHI,"info_template.status"=>self::STATUS_ENABLE,"info_template.display"=>self::DISPLAY_YES,"info_template.type"=>self::TYPE_EMAIL])
                ->groupBy('info_template.id')
                ->orderBy("info_template.id DESC");
            $tmpData = self::arrListByPage($q,$page,$pageSize);
            if (count($tmpData['rows'])) {
                $result = [];
                foreach ($tmpData['rows'] as $k => $v) {
                    $result[$k]['id'] = $v['id'];
                    $result[$k]['link'] = CommonUtil::generateUrl($v['id'],Constant::ROUTE_SUBSCRIBE);
                    $result[$k]['subject'] = $v['subject'];
                    $result[$k]['description'] = $v['description'];
                    $result[$k]['created_at'] = date('Y-m-d',$v['created_at']);
                }
                $data['total'] = $tmpData['total'];
                $data['rows'] = $result;
                if (count($data['rows'])) {
                    CommonUtil::setCache(__CLASS__,$cache_key,$data,86400);
                }
            }
        }
        return $data;
    }

    public static function getUpTemplate() {
        $key = 'template:subject';
        $title = CommonUtil::getCache(__CLASS__,$key);
        if(!$title) {
            $title = self::find()->select('info_template.subject')
                ->join('left join','base_periodical','info_template.id = base_periodical.template_id')
                ->where(["base_periodical.status"=>Periodical::STATUS_FINISHI,"info_template.status"=>self::STATUS_ENABLE,"info_template.display"=>self::DISPLAY_YES,"info_template.type"=>self::TYPE_EMAIL])
                ->groupBy('info_template.id')
                ->orderBy("info_template.id DESC")
                ->asArray()
                ->one();
            if(isset($title['subject'])&&$title['subject']) {
                $title = $title['subject'];
                CommonUtil::setCache(__CLASS__,$key,$title,600);
            }
        }
        return $title;
    }

    /**
     * @param $content
     * @param array $preg_arr
     * @return mixed
     */
    public static function removeTag($content,$preg_arr= ["/<a .*?>退.*?订<\/a>/","/<p .*?{FULLNAME}.*?<\/p>/","/<p .*?id=\"name_for_tag\">.*?<\/p>/","/<p .*?class=\"content_for_remove\">.*?<\/p>/"]) {
        foreach ($preg_arr as $preg) {
            preg_match_all($preg,$content,$match);
            if ($match[0]) {
                foreach ($match[0] as $value) {
                    $content = str_replace($value,'',$content);
                }
            }
        }
        return $content;
    }

}
